package com.ytc.order.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ytc.commons.constants.OrdersConstants;
import com.ytc.commons.enums.ErrorCode;
import com.ytc.commons.model.dto.CourseOrderDto;
import com.ytc.commons.model.dto.PageRequest;
import com.ytc.commons.model.dto.RecordDto;
import com.ytc.commons.model.vo.*;
import com.ytc.commons.utils.BeanHelper;
import com.ytc.learning.api.LearningClient;
import com.ytc.order.domain.Orders;
import com.ytc.order.domain.Payment;
import com.ytc.order.mappers.OrdersMapper;
import com.ytc.order.mappers.PaymentMapper;
import com.ytc.order.service.OrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ytc.order.service.PaymentService;
import com.ytc.order.utils.PayUtils;
import com.ytc.search.api.SearchClient;
import com.ytc.web.exception.BusinessException;
import com.ytc.web.interceptor.AuthInfoHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author jiuye145
 * @since 2023-04-09
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper,Orders> implements OrdersService {


    @Autowired
    private SearchClient searchClient;

    //创建订单
    @Override
    public ResponseResult<String> create (Long coursePubId){
        Long userId=AuthInfoHolder.getUserId();
        //1.查询当前用户是否已经有已支付的订单数据
        LambdaQueryWrapper<Orders> qw=new LambdaQueryWrapper<>();
        qw.eq(Orders::getUserId,userId);
        qw.eq(Orders::getCoursePubId,coursePubId);
        qw.eq(Orders::getStatus,OrdersConstants.ORDER_PAID_STATUS);
        Orders one=this.getOne(qw);
        if(one!=null) {
            throw new BusinessException(ErrorCode.ORDERERROR);
        }
        //2.查询当前用户是否有已经下单，待支付的订单数据，如果存在返回
        LambdaQueryWrapper<Orders> qw1=new LambdaQueryWrapper<>();
        qw1.eq(Orders::getUserId,userId);
        qw1.eq(Orders::getCoursePubId,coursePubId);
        qw1.eq(Orders::getStatus,OrdersConstants.ORDER_INIT_STATUS);
        one=this.getOne(qw1);
        if(one!=null) {
            return ResponseResult.okResult(one.getOrderNo());
        }

        //3.调用feign接口,查询当前课程发布数据
        ResponseResult<CoursePubIndexVo> result=searchClient.findById(coursePubId);
        CoursePubIndexVo vo=result.getData();
        //4.构造Order对象，设置属性
        Orders orders=new Orders();
        orders.setOrderNo(UUID.randomUUID().toString(true));
        orders.setCoursePubName(vo.getName());
        orders.setCoursePubId(coursePubId);
        orders.setCompanyId(vo.getCompanyId());
        orders.setUserId(userId);
        orders.setCreateDate(new Date());
        orders.setPrice(1l); //价格是一分
        orders.setStatus(OrdersConstants.ORDER_INIT_STATUS);
        //5.保存到数据库中
        this.save(orders);

        return ResponseResult.okResult(orders.getOrderNo());
    }

    @Autowired
    private PayUtils payUtils;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private LearningClient learningClient;

    //根据OrderNo查询。订单的支付状态
    @Override
    public ResponseResult<OrdersVo> queryOrders (String orderNo){
        //1.根据订单orderNo查询订单
        LambdaQueryWrapper<Orders> qw=new LambdaQueryWrapper<>();
        qw.eq(Orders::getOrderNo,orderNo);
        Orders orders=this.getOne(qw);
        //2.如果订单不存在。抛异常
        if(orders==null) {
            throw new BusinessException(ErrorCode.NOTFOUND);
        }
        //3.如果存在且未支付状态
        if(orders.getStatus().equals(OrdersConstants.ORDER_INIT_STATUS)) {
            //4.查询微信支付状态。如果支付成功
            Boolean aBoolean=payUtils.checkPayment(orderNo);
            if(aBoolean) {
                //4.1更新订单表
                orders.setStatus(OrdersConstants.ORDER_PAID_STATUS);
                this.updateById(orders);
                //4.2更新支付表
                LambdaQueryWrapper<Payment> wq=new LambdaQueryWrapper<>();
                wq.eq(Payment::getOrderNo,orderNo);
                Payment one=paymentService.getOne(wq);
                one.setStatus(OrdersConstants.PAID.toString());
                //更新支付表
                paymentService.updateById(one);

                //4.3调用feign接口。保存或者更新选课记录
                RecordDto dto=new RecordDto();
                dto.setUserId(AuthInfoHolder.getUserId());
                dto.setCoursePubId(orders.getCoursePubId());
                learningClient.saveRecord(dto);
            }
        }
        //返回
        OrdersVo ordersVo=BeanHelper.copyProperties(orders,OrdersVo.class);
        return ResponseResult.okResult(ordersVo);
    }

    @Override
    public ResponseResult<CourseOrderVo> ordersList (PageRequest request,CourseOrderDto dto){
        //创建分页参数
        Page<Orders> pageParam=new Page<>(request.getPageNo(),request.getPageSize());
//        //创建查询条件
        LambdaQueryWrapper<Orders> qw=new LambdaQueryWrapper<>();
        //获取用户id,查询该用户下的订单信息
        Long userId=AuthInfoHolder.getUserId();
        if(!userId.equals("") && userId!=null) {
            qw.eq(Orders::getUserId,userId);
        }
        if(!"".equals(dto.getOrderNo()) && dto.getOrderNo()!=null) {
            String orderNo=dto.getOrderNo();//订单号
            qw.like(Orders::getOrderNo,orderNo);
        }
        if(!"".equals(dto.getOrderStart()) && dto.getOrderStart()!=null) {
            String orderStart=dto.getOrderStart();//开始时间
            qw.le(Orders::getCreateDate,orderStart);
        }

        if(!"".equals(dto.getOrderEnd()) && dto.getOrderEnd()!=null) {
            String orderEnd=dto.getOrderEnd();//结束时间
            qw.ge(Orders::getCreateDate,orderEnd);
        }
//        if(!"".equals(dto.getPayMethod()) && dto.getPayMethod()!=null) {
//            String payMethod=dto.getPayMethod();//支付方式
//            qw.like(Payment::getPayMethod,payMethod);
//        }
// 课程名称
        if("".equals(dto.getCourseName()) && dto.getCourseName()!=null) {
            qw.like(Orders::getCoursePubName,dto.getCourseName());
        }//订单状态
        if(!dto.getStatus().equals("") && dto.getStatus()!=null) {
            qw.eq(Orders::getStatus,dto.getStatus());
        }
        //分页查询
        Page<Orders> page=this.page(pageParam,qw);
        List<Orders> records=page.getRecords();
        List<CourseOrderVo> vos=new ArrayList<>();
        for(Orders record : records) {
            CourseOrderVo vo=BeanHelper.copyProperties(record,CourseOrderVo.class);
            vo.setContentScore(4l);
            vos.add(vo);
        }
        return new PageResponseResult(page.getTotal(),vos);
    }


}
